package com.file.controller;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javax.validation.constraints.NotBlank;

import cn.hutool.core.util.IdUtil;
import com.qianya.model.common.CommonResult;
import com.qianya.model.common.ResultCode;
import com.qianya.util.DateUtils;
import com.qianya.util.FileManage;
import com.qianya.util.FileUtil;
import com.qianya.util.SystemConfig;
import com.qianya.util.dtree.EleTreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lhl
 * @since 2019-08-16
 */
@RestController
@RequestMapping("/file/file-manage")
@Slf4j
@Api(value = "FileManageController",tags = "文件资源管理接口")
@Validated
public class FileManageController{
    /**
     * @desc 获得文件树列表
     * @author lhl
     * @date 2020-07-13 14:47
     * @return
    */
   // @ApiOperation("获得文件树列表")
    @GetMapping(value = "/dTreeList",produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult dTreeList() {
        try {
            List<FileManage> list = FileUtil.getFiles(SystemConfig.filePath(), true);
            list.add(new FileManage("根目录", File.separator, "0", null, null, true, null));
            return CommonResult.success(EleTreeUtil.getResp(list, "path", "parentPath", "name"));
        }catch (Exception e) {
            log.error("文件树列表异常===》"+e.getMessage());
            return CommonResult.error(ResultCode.ERROR);
        }
    }
    /**
     * @desc  根据文件夹获得其下文件
     * @author lhl
     * @date 2020-07-13 14:48
     * @return
     */
    @ApiOperation("根据文件夹获得其下文件")
    @GetMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult list(@ApiParam(value = "文件地址",required = false)
                                 @RequestParam(defaultValue = "",name = "path") String path) {
        try {
            ArrayList<FileManage> list = (ArrayList<FileManage>) FileUtil.getFiles(SystemConfig.filePath()+path, false);
            list.sort((f1,f2) -> f2.getIsDirectory().compareTo(f1.getIsDirectory()));
            return CommonResult.success(list);
        }catch (Exception e) {
            log.error("文件列表异常===》"+e.getMessage());
            return CommonResult.error(ResultCode.ERROR);
        }
    }
    /**
     * @desc
     * @author lhl
     * @date 2020-07-13 14:49
     * @return
    */
    @ApiOperation("根据文件路径获得文件内容")
    @GetMapping(value = "/getFileContent",produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult getFileContent(@ApiParam(value = "文件地址",required = true)
                                           @NotBlank(message = "地址不能为空" )
                                            @RequestParam(defaultValue = "",name = "path") String path) {
        Map<String,String> map=new HashMap<String,String>();
        map.put("path",path);
        map.put("content",FileUtil.read(SystemConfig.filePath()+path));
        return CommonResult.success(map);
    }
    @ApiOperation("修改文件内容")
    @PutMapping(value = "/editFile",produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult editFile(@ApiParam(value = "文件地址",required = true)
                                     @NotBlank(message = "地址不能为空" )
                                     @RequestParam(defaultValue = "",name = "path") String path,
                                 @ApiParam(value = "文件内容",required = true)
                                 @NotBlank(message = "内容不能为空" )
                                 @RequestParam(defaultValue = "",name = "content") String content) {
        try {
            FileUtil.write(SystemConfig.filePath()+path, content);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("写入文件异常===>"+e.getMessage());
            return CommonResult.error(ResultCode.ERROR);
        }
    }

    @ApiOperation("根据文件名删除文件")
    @GetMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult delete(@ApiParam(value = "文件名",required = true)
                                   @NotBlank(message = "文件名不能为空" )
                                   @RequestParam(defaultValue = "",name = "path") String path) {
        try {
            FileUtil.delete(SystemConfig.filePath()+path);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("写入删除异常===>"+e.getMessage());
            return CommonResult.error(ResultCode.ERROR);
        }
    }
    /**
     * @param file
     * @param basePath
     * @return
     * @Desc 上传文件
     * @author Lhl
     * @Date 2019年8月19日 下午2:26:09
     */
    @PostMapping(value = "/fileUpload",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("上传图片")
    public CommonResult fileUpload( MultipartFile file,
                                   @ApiParam(value = "文件夹名",required = true)
                                   @RequestParam(defaultValue = "",name = "basePath")String basePath) {
        if ("".equals(basePath.trim())){
            return CommonResult.error(ResultCode.ERROR,"请输入文件夹名");
        }
        String absolutePath = SystemConfig.filePath() + File.separator + "upload" + File.separator + basePath;
        String relativePath = File.separator + "statics" + File.separator + "upload" + File.separator + basePath;
        try {
            String filePath = getFilePath(file.getOriginalFilename(), absolutePath, 1);
            Path path = Paths.get(absolutePath + filePath);
            Files.createDirectories(path.getParent());
            Files.write(path, file.getBytes());
            Map<String, String> map = new HashMap<>();
            map.put("path", relativePath + filePath);
           // map.put("realPath", absolutePath + filePath);
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(ResultCode.ERROR,"图片上传失败");
        }
    }
    private String getFilePath(String fileName, String absolutePath, int level) {
        String fileNameWithoutSuffix = fileName.substring(0, fileName.lastIndexOf("."));
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String time = DateUtils.format(new Date(), "yyyyMMdd");
        File file = new File(absolutePath + File.separator + time + File.separator + fileName);
        if (file.exists()) {
            return getFilePath(fileNameWithoutSuffix + "" + IdUtil.simpleUUID() + "." + suffixName, absolutePath, level + 1);
        }
        return File.separator + time + File.separator + fileName;
    }
}
